package pers.cyril.jdb.client.netty.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import pers.cyril.jdb.client.sender.ConsoleLoginSender;
import pers.cyril.jdb.client.sender.ConsoleScriptSender;
import pers.cyril.jdb.common.channel.Session;
import pers.cyril.jdb.common.util.SessionUtils;
import pers.cyril.jdb.protocol.packet.LoginResponsePacket;


/**
 * 说点什么吧
 *
 * @author ziv
 * @date 2021/12/7 20:32
 */
@ChannelHandler.Sharable
public class LoginResponseHandler extends SimpleChannelInboundHandler<LoginResponsePacket> {
    public static final LoginResponseHandler INSTANCE = new LoginResponseHandler();

    private LoginResponseHandler() {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginResponsePacket msg) throws Exception {
        if (msg.isSuccess()) {
            Session session = new Session();
            session.setUserId(msg.getUserId());
            session.setUsername(msg.getUsername());
            SessionUtils.attachSession(ctx.channel(), session);
            System.out.println("【" + msg.getUsername() + "】登录成功! 用户标识: " + msg.getUserId());
            ConsoleScriptSender.INSTANCE.send(ctx.channel());
        } else {
            System.out.println(msg.getMessage());
            if (!SessionUtils.hasSession(ctx.channel())) {
                ConsoleLoginSender.INSTANCE.send(ctx.channel());
            }
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionUtils.removeSession(ctx.channel());
        System.out.println("连接已经关闭，会话已退出");
    }


}
